//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { listen, type UnlistenFn, type Event } from '@tauri-apps/api/event';
import { makeAutoObservable, runInAction } from "mobx";
import type * as NoticeType from '@/api/notice_type';
import type { TrigerInfo } from "@/api/project_triger";
import { list as list_triger,get as get_triger } from "@/api/project_triger";
import { get_session } from '@/api/user';
import { request } from '@/utils/request';

export class LocalDevflowTrigerStore {
    constructor(projectId: string, pageSize: number) {
        this._projectId = projectId;
        this._pageSize = pageSize;
        makeAutoObservable(this);
        this.loadTrigerList();
        listen<NoticeType.AllNotice>('notice', (ev) => {
            this.processEvent(ev);
        }).then(unlistenFn => this._unlistenFn = unlistenFn);
    }
    private _projectId: string;

    private _unlistenFn: UnlistenFn | null = null;

    private _itemList: TrigerInfo[] = [];
    private _pageSize: number;
    private _totalCount = 0;
    private _curPage = 0;

    unlisten() {
        if (this._unlistenFn != null) {
            this._unlistenFn();
        }
    }

    get itemList() {
        return this._itemList;
    }

    get pageSize() {
        return this._pageSize;
    }

    get totalCount() {
        return this._totalCount;
    }

    get curPage() {
        return this._curPage;
    }

    set curPage(val:number){
        if(this._curPage == val){
            return;
        }
        runInAction(()=>{
            this._curPage = val;
        });
        this.loadTrigerList();
    }

    private async loadTrigerList() {
        const sessionId = await get_session();
        const res = await request(list_triger({
            session_id: sessionId,
            project_id: this._projectId,
            offset: this._pageSize * this._curPage,
            limit: this._pageSize,
        }));
        runInAction(()=>{
            this._totalCount = res.total_count;
            this._itemList = res.triger_list;
        });
    }

    private async processEvent(ev: Event<NoticeType.AllNotice>) {
        if (ev.payload.TrigerNotice !== undefined) {
            if(ev.payload.TrigerNotice.CreateTrigerNotice !== undefined && ev.payload.TrigerNotice.CreateTrigerNotice.project_id == this._projectId) {
                await this.onCreate();
            }else if(ev.payload.TrigerNotice.UpdateTrigerNotice !== undefined && ev.payload.TrigerNotice.UpdateTrigerNotice.project_id == this._projectId){
                await this.onUpdate(ev.payload.TrigerNotice.UpdateTrigerNotice.triger_id);
            }else if(ev.payload.TrigerNotice.RemoveTrigerNotice !== undefined && ev.payload.TrigerNotice.RemoveTrigerNotice.project_id == this._projectId){ 
                await this.onRemove(ev.payload.TrigerNotice.RemoveTrigerNotice.triger_id);
            }
        }
    }

    private async onCreate() {
        if(this._curPage != 0){
            this.curPage = 0;
        }else{
            await this.loadTrigerList();
        }
    }

    private async onUpdate(trigerId:string) {
        const tmpList = this._itemList.slice();
        const index = tmpList.findIndex(item=>item.triger_id == trigerId);
        if (index == -1){
            return;
        }
        
        const sessionId = await get_session();
        const res = await request(get_triger({
            session_id: sessionId,
            project_id: this._projectId,
            triger_id: trigerId,
        }));
        tmpList[index] = res.triger;
        runInAction(()=>{
            this._itemList = tmpList;
        });
    }

    private async onRemove(trigerId:string) {
        const tmpList = this._itemList.slice();
        const index = tmpList.findIndex(item=>item.triger_id == trigerId);
        if (index == -1){
            return;
        }
        await this.loadTrigerList();
    }
}